# -*- coding: utf-8 -*-

from flask import request,jsonify
from . import user
from app.models import*
from app.route.verify_common import *
from modules.TimeManage.timetool import timeToStr
import uuid


'''
输入appid 与控制时间/ 返回appkey
{
    'user_appid':'xxxxx',
    'user_time_control':"2020-07-22T12:22:12",
}
'''
@user.route('/generate',methods=['POST'])
def web_user_generate():
    try:
        data = request.get_data()
        json_data =json.loads(data)
        if json_data['user_appid']:
            #待做user_appid基本校验,数据查重
            app_filter_res = Spiderdb.query.filter(Spiderdb.user_appid == json_data['user_appid'])
            print(app_filter_res.count())
            if app_filter_res.count() >0:
                return json.dumps({'status':-3,'msg':u'user_appid存在','data':app_filter_res.first().to_json()})
            #不存在当前appid
            json_data['user_appkey'] = str(uuid.uuid1())
            json_data['user_insert_time'] = timeToStr(time.time())
            json_data['user_last_use_time'] = json_data['user_insert_time']
            json_data['user_token'] = 'default'

            tmp = Spiderdb( json_data['user_insert_time'],
                            json_data['user_last_use_time'],
                            json_data['user_appid'],
                            json_data['user_time_control'],
                            json_data['user_appkey'],
                            json_data['user_token']
                            )
            print(tmp)
            db.session.add(tmp)
            db.session.commit() 
            return json.dumps({'status':1,'msg':u'生成成功','data':json_data})
    except Exception as err:
        print('err:',err)
        return json.dumps({'status':-1,'msg':str(err)})

#测试用接口
@user.route('/get_all',methods=['GET'])
def web_user_get_all():
    result_db1 = list(Spiderdb.query.all())
    result_db2 = list(SpiderWork.query.all())
    tmp_dict = {
        'result1':[],
        'result2':[]
        }
    for item in result_db1:
        tmp_dict['result1'].append(item.to_json())
    for item in result_db2:
        tmp_dict['result2'].append(item.to_json())
    return json.dumps(tmp_dict)